﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using System.IO;
using Microsoft.Xna.Framework.Graphics;
using Brain.IO;
using Brain.Editor;

namespace Brain
{
    public class HeightMap : IEditorNeedsSave
    {
        public int Width;
        public int Height;

        public float OffsetBetweenHeights = 2;

        /// <summary>
        /// CPU stored data - Might be destroyed right
        /// after loading into the GPU
        /// </summary>
        public float[,] Heights;

        /// <summary>
        /// CPU stored data - Might be destroyed right
        /// after loading into the GPU
        /// </summary>
        public Vector3[,] Normals;

        public HeightMap()
        {
        }

        public bool Intersects(BoundingSphere sphere, float height, int heightIndexX, int heightIndexZ)
        {
            return sphere.Contains(new Vector3(heightIndexX * OffsetBetweenHeights, height, -heightIndexZ * OffsetBetweenHeights))
                == ContainmentType.Contains;
        }
        public bool Intersects(BoundingSphere sphere, int heightIndexX, int heightIndexZ)
        {
            float height = Heights[heightIndexX, heightIndexZ];
            return sphere.Contains(new Vector3(heightIndexX * OffsetBetweenHeights, height, -heightIndexZ * OffsetBetweenHeights)) 
                == ContainmentType.Contains;
        }

        /// <summary>
        /// Reads a Heightmap from a Texture
        /// </summary>
        /// <param name="Texture"></param>
        /// <param name="factor">How much to multiply the heights</param>
        public void ReadFromTexture(Texture2D Texture,
            float factor)
        {
            Width = Texture.Width;
            Height = Texture.Height;

            Color[] Colors = new Color[Width * Height];
            Texture.GetData(Colors);

            Heights = new float[Width, Height];

            for (int x = 0; x < Width; x++)
            {
                for (int y = 0; y < Height; y++)
                {
                    Heights[x, y] = (float)Colors[x + y * Width].R * factor;
                }
            }
        }

        public void EditorSaving(SceneContentFile file)
        {
            TerrainFile terrain = new TerrainFile();
            terrain.Heights = this.Heights;
            terrain.DistanceBetweenHeights = this.OffsetBetweenHeights;

            if (File.Exists(file.ProcessedPath))
            {
                File.Delete(file.ProcessedPath);
            }

            using (FileStream stream = new FileStream(file.ProcessedPath, FileMode.Create))
            {
                terrain.Serialize(stream);
            }
        }
    }
}
